package com.ruoyi.factorydata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factorydata.domain.*;
import com.ruoyi.factorydata.domain.dto.ModelInventoryPrintDTO;
import com.ruoyi.factorydata.domain.dto.ModelInventoryPrintDetailDTO;
import com.ruoyi.factorydata.domain.dto.ProductInventoryPrintDetailDTO;
import com.ruoyi.factorydata.mapper.InventoryReceiptDetailMapper;
import com.ruoyi.factorydata.mapper.InventoryReceiptInfoMapper;
import com.ruoyi.factorydata.mapper.InventoryReceiptModelDetailMapper;
import com.ruoyi.factorydata.mapper.PrintTemplateMapper;
import com.ruoyi.factorydata.service.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 入库单信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-21
 */
@Service
public class InventoryReceiptInfoServiceImpl extends ServiceImpl<InventoryReceiptInfoMapper, InventoryReceiptInfo> implements IInventoryReceiptInfoService {
    private final InventoryReceiptInfoMapper inventoryReceiptInfoMapper;
    private final InventoryReceiptDetailMapper inventoryReceiptDetailMapper;
    private final InventoryReceiptModelDetailMapper inventoryReceiptModelDetailMapper;
    private final ISysUserService sysUserService;
    private final IWarehouseInfoService warehouseInfoService;
    private final IWarehousePositionService warehousePositionService;
    private final IPurchaseOrderInfoService purchaseOrderInfoService;
    private final IMaterialUnitDataService materialUnitDataService;
    private final IMaterialInventoryService materialInventoryService;
    private final IModelInventoryService modelInventoryService;
    private final IWorkOrderInfoService workOrderInfoService;
    private final IWorkOrderLogService workOrderLogService;
    private final ISysConfigService sysConfigService;
    private final IPrintTemplateService printTemplateService;
    private final ICustomerDataService customerDataService;
    private final ISysDictDataService sysDictDataService;

    private final PrintTemplateMapper printTemplateMapper;
    public InventoryReceiptInfoServiceImpl(InventoryReceiptInfoMapper inventoryReceiptInfoMapper,
                                           InventoryReceiptDetailMapper inventoryReceiptDetailMapper,
                                           InventoryReceiptModelDetailMapper inventoryReceiptModelDetailMapper,
                                           ISysUserService sysUserService,
                                           IWarehouseInfoService warehouseInfoService,
                                           IWarehousePositionService warehousePositionService,
                                           IPurchaseOrderInfoService purchaseOrderInfoService,
                                           IMaterialUnitDataService materialUnitDataService,
                                           IMaterialInventoryService materialInventoryService,
                                           IModelInventoryService modelInventoryService,
                                           IWorkOrderInfoService workOrderInfoService,
                                           IWorkOrderLogService workOrderLogService,
                                           ISysConfigService sysConfigService,
                                           IPrintTemplateService printTemplateService,
                                           ICustomerDataService customerDataService,
                                           ISysDictDataService sysDictDataService,
                                           PrintTemplateMapper printTemplateMapper) {
        this.inventoryReceiptInfoMapper = inventoryReceiptInfoMapper;
        this.inventoryReceiptDetailMapper = inventoryReceiptDetailMapper;
        this.inventoryReceiptModelDetailMapper = inventoryReceiptModelDetailMapper;
        this.sysUserService = sysUserService;
        this.warehouseInfoService = warehouseInfoService;
        this.warehousePositionService = warehousePositionService;
        this.purchaseOrderInfoService = purchaseOrderInfoService;
        this.materialUnitDataService = materialUnitDataService;
        this.materialInventoryService = materialInventoryService;
        this.modelInventoryService = modelInventoryService;
        this.workOrderInfoService = workOrderInfoService;
        this.workOrderLogService = workOrderLogService;
        this.sysConfigService = sysConfigService;
        this.printTemplateService = printTemplateService;
        this.customerDataService = customerDataService;
        this.sysDictDataService = sysDictDataService;
        this.printTemplateMapper = printTemplateMapper;
    }

    /**
     * 查询入库单信息
     *
     * @param id 入库单信息主键
     * @return 入库单信息
     */
    @Override
    public InventoryReceiptInfo selectInventoryReceiptInfoById(Long id) {
        InventoryReceiptInfo inventoryReceiptInfo = inventoryReceiptInfoMapper.selectInventoryReceiptInfoById(id);
        HashMap<Long, String> unitNameCache = new HashMap<>();
        HashMap<Long, String> positionNameCache = new HashMap<>();
        HashMap<Long, String> sysUserCache = new HashMap<>();
        HashMap<Long, String> customCache = new HashMap<>();

        String warehousePositionName = null;
        //采购单入库
        if (inventoryReceiptInfo.getReceiptType() == 1|| inventoryReceiptInfo.getReceiptType() == 3) {
            List<InventoryReceiptDetail> inventoryReceiptDetails = inventoryReceiptDetailMapper.selectInventoryReceiptDetailList(InventoryReceiptDetail
                    .builder()
                    .receiptNumber(inventoryReceiptInfo.getReceiptNumber())
                    .build());
            inventoryReceiptDetails.forEach(inventoryReceiptDetail -> {
                String unitName = materialUnitDataService.getByIdAndCache(Long.valueOf(inventoryReceiptDetail.getUnit()), unitNameCache);
                String positionName = warehousePositionService.getByIdAndCache(inventoryReceiptDetail.getWarehousePositionId(), positionNameCache);
                inventoryReceiptDetail.setMaterialUnitName(unitName);
                inventoryReceiptDetail.setWarehousePositionName(positionName);
            });
            if(inventoryReceiptInfo.getReceiptType() == 1){
                PurchaseOrderInfo purchaseOrderInfo = purchaseOrderInfoService.getById(inventoryReceiptInfo.getPurchaseOrderId());
                String purchaseOrderApplyName = sysUserService.getUserNameByIdAndCache(Long.parseLong(purchaseOrderInfo.getCreateBy()), sysUserCache);
                if(StringUtils.isNotBlank(inventoryReceiptInfo.getPurchaseOrderAuth())){
                    String purchaseOrderAuthName = sysUserService.getUserNameByIdAndCache(Long.parseLong(inventoryReceiptInfo.getPurchaseOrderAuth()), sysUserCache);
                    inventoryReceiptInfo.setPurchaseOrderAuthName(purchaseOrderAuthName);
                }
                inventoryReceiptInfo.setPurchaseOrderApplyName(purchaseOrderApplyName);

                inventoryReceiptInfo.setPurchaseOrderTime(purchaseOrderInfo.getCreateTime());
            }else if (inventoryReceiptInfo.getReceiptType() == 3){
                WorkOrderInfo workOrderInfo = workOrderInfoService.getById(inventoryReceiptInfo.getWorkOrderId());
                String workOrderApplyName = sysUserService.getUserNameByIdAndCache(Long.parseLong(inventoryReceiptInfo.getCreateBy()), sysUserCache);
                inventoryReceiptInfo.setWorkOrderFinishTime(workOrderInfo.getActualEndTime());
                inventoryReceiptInfo.setWorkOrderApplyName(workOrderApplyName);
            }
            inventoryReceiptInfo.setInventoryReceiptDetailList(inventoryReceiptDetails);

        } else if (inventoryReceiptInfo.getReceiptType() == 2|| inventoryReceiptInfo.getReceiptType() == 4|| inventoryReceiptInfo.getReceiptType() == 5) {
            //母版入库
            List<InventoryReceiptModelDetail> inventoryReceiptModelDetails = inventoryReceiptModelDetailMapper.selectInventoryReceiptModelDetailList(InventoryReceiptModelDetail
                    .builder()
                    .receiptNumber(inventoryReceiptInfo.getReceiptNumber())
                    .build());
            inventoryReceiptModelDetails.forEach(inventoryReceiptModelDetail -> {
                String positionName = warehousePositionService.getByIdAndCache(inventoryReceiptModelDetail.getWarehousePositionId(), positionNameCache);
                inventoryReceiptModelDetail.setWarehousePositionName(positionName);
            });
            inventoryReceiptInfo.setInventoryReceiptModelDetailList(inventoryReceiptModelDetails);
            warehousePositionName = inventoryReceiptModelDetails.get(0).getWarehousePositionName();
        }


        String warehouseName = warehouseInfoService.getNameByIdAndCache(inventoryReceiptInfo.getWarehouseId(), new HashMap<>());
        String supplierName = sysUserService.getUserNameByIdAndCache(inventoryReceiptInfo.getSupplierId(), sysUserCache);
        String createByName = sysUserService.getUserNameByIdAndCache(Long.parseLong(inventoryReceiptInfo.getCreateBy()), sysUserCache);
        String customCode = customerDataService.getCodeByIdAndCache(inventoryReceiptInfo.getCustomerId(), customCache);

        if (inventoryReceiptInfo.getHandlerId() != null) {
            String handlerName = sysUserService.getUserNameByIdAndCache(inventoryReceiptInfo.getHandlerId(), new HashMap<>());
            inventoryReceiptInfo.setHandlerName(handlerName);
        }
        inventoryReceiptInfo.setCreateByName(createByName);
        inventoryReceiptInfo.setWarehouseName(warehouseName);
        inventoryReceiptInfo.setSupplierName(supplierName);
        inventoryReceiptInfo.setWarehousePositionName(warehousePositionName);
        inventoryReceiptInfo.setCustomCode(customCode);

        return inventoryReceiptInfo;
    }

    /**
     * 查询入库单信息列表
     *
     * @param inventoryReceiptInfo 入库单信息
     * @return 入库单信息
     */
    @Override
    public List<InventoryReceiptInfo> selectInventoryReceiptInfoList(InventoryReceiptInfo inventoryReceiptInfo) {
        HashMap<Long, String> createByCache = new HashMap<>();
        HashMap<Long, String> warehouseCache = new HashMap<>();
        List<InventoryReceiptInfo> inventoryReceiptInfos = inventoryReceiptInfoMapper.selectInventoryReceiptInfoList(inventoryReceiptInfo);
        for (InventoryReceiptInfo receiptInfo : inventoryReceiptInfos) {
            String createByName = sysUserService.getUserNameByIdAndCache(Long.parseLong(receiptInfo.getCreateBy()), createByCache);
            String warehouseName = warehouseInfoService.getNameByIdAndCache(receiptInfo.getWarehouseId(), warehouseCache);
            String supplierName = sysUserService.getUserNameByIdAndCache(receiptInfo.getSupplierId(), createByCache);
            Long expectedQuantityTotal = 0L;
            if (receiptInfo.getReceiptType() == 1|| receiptInfo.getReceiptType() == 3) {
                expectedQuantityTotal = inventoryReceiptDetailMapper.getExpectedQuantityTotal(receiptInfo.getId());
            } else {
                expectedQuantityTotal = inventoryReceiptModelDetailMapper.getExpectedQuantityTotal(receiptInfo.getId());
            }

            receiptInfo.setWarehouseName(warehouseName);
            receiptInfo.setSupplierName(supplierName);
            receiptInfo.setCreateByName(createByName);
            receiptInfo.setExpectedQuantityTotal(expectedQuantityTotal);
        }
        return inventoryReceiptInfos;
    }


    @Override
    public ModelInventoryPrintDTO getPrintInfo(Long id) {
        InventoryReceiptInfo receiptInfo = selectInventoryReceiptInfoById(id);
        Assert.notNull(receiptInfo, "入库单信息不存在");
        Assert.notNull(receiptInfo.getReceiptType(), "入库单信息不存在");
        Assert.isTrue(receiptInfo.getReceiptType()==2
                ||receiptInfo.getReceiptType()==4
                ||receiptInfo.getReceiptType()==5, "入库单类型错误");
        String inventoryReceiptType = sysDictDataService.selectDictLabel("inventory_receipt_type", receiptInfo.getReceiptType() + "");
        String modelPrintDetailUrl = sysConfigService.selectConfigByKey("modelPrintDetailUrl");
        Assert.notNull(modelPrintDetailUrl, "母版详情未配置");
        HashMap<Long, String> customNameCache = new HashMap<>();
        String customerName = customerDataService.getCodeByIdAndCache(receiptInfo.getCustomerId(), customNameCache);
        List<InventoryReceiptModelDetail> inventoryReceiptModelDetailList = receiptInfo.getInventoryReceiptModelDetailList();
        Assert.notNull(inventoryReceiptModelDetailList, "入库单信息不存在");
        List<ModelInventoryPrintDetailDTO> printDetailDTOList = inventoryReceiptModelDetailList.stream().map(inventoryReceiptModelDetail -> {
            String modelLevelOption = sysDictDataService.selectDictLabel("model_level_option", inventoryReceiptModelDetail.getModelLevel());
            return ModelInventoryPrintDetailDTO.builder()
                    .qrCode(modelPrintDetailUrl+"?inventoryReceiptId=" + receiptInfo.getId())
                    .customId(StringUtils.isNotBlank(customerName)?customerName:"自有")
                    .modelNum(inventoryReceiptModelDetail.getModelNumber())
                    .productionDate(DateFormatUtils.format(inventoryReceiptModelDetail.getProductionDate(), "yyyy/MM/dd"))
                    .modelMaterial(inventoryReceiptModelDetail.getModelMaterial())
                    .modelLevel(modelLevelOption)
                    .warehousePosition(inventoryReceiptModelDetail.getWarehousePositionCode())
                    .inventoryReceiptType(inventoryReceiptType)
                    .build();
        }).collect(Collectors.toList());
        PrintTemplate printTemplate = printTemplateService
                .lambdaQuery()
                .eq(PrintTemplate::getPrintType, "modelInventoryReceipt")
                .orderByDesc(PrintTemplate::getId)
                .last(" limit 1")
                .one();
        Assert.notNull(printTemplate, "打印模板不存在");
        return ModelInventoryPrintDTO.builder()
                .templateName(printTemplate.getPrintType())
                .template(printTemplate.getContent())
                .detailList(printDetailDTOList)
                .build();
    }

    @Override
    public ProductInventoryPrintDetailDTO getProductPrintInfo(Long id) {
        InventoryReceiptInfo receiptInfo = selectInventoryReceiptInfoById(id);
        Assert.notNull(receiptInfo, "入库单信息不存在");
        Assert.notNull(receiptInfo.getReceiptType(), "入库单信息不存在");
        Assert.isTrue(receiptInfo.getReceiptType()==3, "入库单类型错误");
        List<InventoryReceiptDetail> inventoryReceiptDetails = inventoryReceiptDetailMapper.selectInventoryReceiptDetailList(InventoryReceiptDetail.builder().receiptId(id).build());
        Assert.isTrue(inventoryReceiptDetails!=null&&inventoryReceiptDetails.size()==1, "入库单信息错误");
        InventoryReceiptDetail inventoryReceiptDetail = inventoryReceiptDetails.get(0);

        String webSiteUrl = sysConfigService.selectConfigByKey("webSiteUrl");
        Assert.notNull(webSiteUrl, "站点地址未配置");
        receiptInfo.setIsPrint(1);
        inventoryReceiptInfoMapper.updateInventoryReceiptInfo(receiptInfo);
        //获取模板
        PrintTemplate printTemplate = printTemplateMapper.selectOne(new LambdaQueryWrapper<PrintTemplate>()
                .eq(PrintTemplate::getPrintType, "productInfo")
                .last("limit 1")
                .orderByDesc(PrintTemplate::getId)
        );
        Assert.notNull(printTemplate, "打印模板不存在");
        String cutsomCode ="自有";
        if(receiptInfo.getCustomerId()!=null){
            CustomerData customerData = customerDataService.selectCustomerDataById(receiptInfo.getCustomerId());
            if(customerData!=null){
                cutsomCode = customerData.getCustomerCode();
            }
        }
        String expandParams = "-";
        //inventoryReceiptDetail.getMaterialSpecification() 不为空，如果长度大于27则截取
        if(StringUtils.isNotBlank(inventoryReceiptDetail.getMaterialSpecification())){
            if(inventoryReceiptDetail.getMaterialSpecification().length()>27){
               expandParams=inventoryReceiptDetail.getMaterialSpecification().substring(0,27)+"...";
            }else{
                expandParams=inventoryReceiptDetail.getMaterialSpecification();
            }
        }
        return ProductInventoryPrintDetailDTO.builder()
                .template(printTemplate.getContent())
                .templateName(printTemplate.getPrintType())
                .customId(cutsomCode)
                .productNum(inventoryReceiptDetail.getMaterialCode())
                .productionDate(DateFormatUtils.format(receiptInfo.getReceiptDate(),"yyyy-MM-dd"))
                .expandParams(expandParams)
                .warehousePosition(inventoryReceiptDetail.getWarehousePositionCode())
                .qrCode(webSiteUrl+"/warehouse/viewInventoryReceipt?id="+id+"&scanner=1")
                .build();
    }

    /**
     * 新增入库单信息
     *
     * @param inventoryReceiptInfo 入库单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertInventoryReceiptInfo(InventoryReceiptInfo inventoryReceiptInfo) {
        Assert.notNull(inventoryReceiptInfo, "入库单信息不能为空");
        Assert.isTrue(!CollectionUtils.isEmpty(inventoryReceiptInfo.getInventoryReceiptDetailList())
                || !CollectionUtils.isEmpty(inventoryReceiptInfo.getInventoryReceiptModelDetailList()), "入库单信息明细不能为空");
        Assert.isTrue(inventoryReceiptInfo.getReceiptType() == 2
                || inventoryReceiptInfo.getReceiptType() == 3
                || inventoryReceiptInfo.getReceiptType() == 4
                || inventoryReceiptInfo.getReceiptType() == 5, "入库单类型错误");
        inventoryReceiptInfo.setCreateTime(DateUtils.getNowDate());
        inventoryReceiptInfo.setCreateBy(SecurityUtils.getUserId() + "");
        inventoryReceiptInfo.setReceiptNumber("GR" + System.currentTimeMillis());
        int save = inventoryReceiptInfoMapper.insertInventoryReceiptInfo(inventoryReceiptInfo);
        if (save > 0) {
            String batchNumber = DateFormatUtils.format(inventoryReceiptInfo.getCreateTime(), "yyyyMMddHHmmss");
            AtomicReference<Long> inventoryNum= new AtomicReference<>(0L);
            if(inventoryReceiptInfo.getReceiptType()==2||inventoryReceiptInfo.getReceiptType()==4||inventoryReceiptInfo.getReceiptType()==5){
                //母版类型入库
                inventoryReceiptInfo.getInventoryReceiptModelDetailList().forEach(inventoryReceiptModelDetail -> {
                    inventoryReceiptModelDetail.setReceiptNumber(inventoryReceiptInfo.getReceiptNumber());
                    inventoryReceiptModelDetail.setReceiptId(inventoryReceiptInfo.getId());
                    inventoryReceiptModelDetail.setCreateBy(SecurityUtils.getUserId() + "");
                    inventoryReceiptModelDetail.setCreateTime(DateUtils.getNowDate());
                    inventoryReceiptModelDetailMapper.insertInventoryReceiptModelDetail(inventoryReceiptModelDetail);
                    //母版入库单直接入库
                    if (inventoryReceiptInfo.getReceiptType() == 2 && inventoryReceiptInfo.getStatus() == 1) {
                        //生成库存信息
                        modelInventoryService.saveInventoryIn(inventoryReceiptInfo, inventoryReceiptModelDetail, batchNumber);
                    }
                    inventoryNum.updateAndGet(v -> v + inventoryReceiptModelDetail.getExpectedQuantity());
                });
            }else {
                inventoryReceiptInfo.getInventoryReceiptDetailList().forEach(inventoryReceiptDetail -> {
                    inventoryReceiptDetail.setReceiptId(inventoryReceiptInfo.getId());
                    inventoryReceiptDetail.setReceiptNumber(inventoryReceiptInfo.getReceiptNumber());
                    inventoryReceiptDetail.setRemark(inventoryReceiptInfo.getRemark());
                    inventoryReceiptDetail.setCreateBy(inventoryReceiptInfo.getCreateBy());
                    inventoryReceiptDetail.setCreateTime(DateUtils.getNowDate());
                    int insert = inventoryReceiptDetailMapper.insertInventoryReceiptDetail(inventoryReceiptDetail);
                    Assert.isTrue(insert > 0, "入库单明细保存失败");
                    inventoryNum.updateAndGet(v -> v + inventoryReceiptDetail.getExpectedQuantity());
                });
            }
            if(inventoryReceiptInfo.getReceiptType()==3||inventoryReceiptInfo.getReceiptType()==4||inventoryReceiptInfo.getReceiptType()==5){
                WorkOrderInfo workOrderInfo = workOrderInfoService.getById(inventoryReceiptInfo.getWorkOrderId());
                Assert.notNull(workOrderInfo, "工单信息不存在");
                String warehouseType=inventoryReceiptInfo.getReceiptType()==3?"产成品库":inventoryReceiptInfo.getReceiptType()==4?"产成品母版库":"母版库";
                String prefix=inventoryReceiptInfo.getReceiptType()==5?"母版加工":"";
                workOrderLogService.saveLog(workOrderInfo, prefix+"工单申请入`"+warehouseType+"`，入库单编号："
                        +inventoryReceiptInfo.getReceiptNumber()
                        +"，申请入库库存："+inventoryNum.get());
            }
        }
        return save;
    }

    /**
     * 修改入库单信息
     *
     * @param inventoryReceiptInfo 入库单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateInventoryReceiptInfo(InventoryReceiptInfo inventoryReceiptInfo) {
        Assert.notNull(inventoryReceiptInfo, "入库单信息不能为空");
        Assert.notNull(inventoryReceiptInfo.getId(), "入库单信息ID不能为空");
        Assert.isTrue(!CollectionUtils.isEmpty(inventoryReceiptInfo.getInventoryReceiptDetailList())
                || !CollectionUtils.isEmpty(inventoryReceiptInfo.getInventoryReceiptModelDetailList()), "入库单信息明细不能为空");
        WorkOrderInfo workOrderInfo = workOrderInfoService.getById(inventoryReceiptInfo.getWorkOrderId());

        inventoryReceiptInfo.setUpdateTime(DateUtils.getNowDate());
        inventoryReceiptInfo.setUpdateBy(SecurityUtils.getUserId() + "");
        int update = inventoryReceiptInfoMapper.updateInventoryReceiptInfo(inventoryReceiptInfo);
        if (update > 0) {
            Long inventoryNum=0L;
            String batchNumber = DateFormatUtils.format(inventoryReceiptInfo.getCreateTime(), "yyyyMMddHHmmss");
            //生成入库单信息
            if (inventoryReceiptInfo.getStatus() == 1 && (inventoryReceiptInfo.getReceiptType() == 1||inventoryReceiptInfo.getReceiptType() == 3)) {
                //采购单入库
                for (InventoryReceiptDetail inventoryReceiptDetail : inventoryReceiptInfo.getInventoryReceiptDetailList()) {
                    inventoryReceiptDetail.setUpdateTime(DateUtils.getNowDate());
                    inventoryReceiptDetailMapper.updateInventoryReceiptDetail(inventoryReceiptDetail);
                    //生成库存信息
                    materialInventoryService.saveInventoryIn(inventoryReceiptInfo, inventoryReceiptDetail, batchNumber);
                    inventoryNum+=inventoryReceiptDetail.getActualQuantity();
                }
            } else if (inventoryReceiptInfo.getStatus() == 1 && (inventoryReceiptInfo.getReceiptType() == 2
                    ||inventoryReceiptInfo.getReceiptType() == 4
                    ||inventoryReceiptInfo.getReceiptType() == 5)) {
                //母版入库单入库
                for (InventoryReceiptModelDetail inventoryReceiptModelDetail : inventoryReceiptInfo.getInventoryReceiptModelDetailList()) {
                    inventoryReceiptModelDetail.setUpdateTime(DateUtils.getNowDate());
                    inventoryReceiptModelDetailMapper.updateInventoryReceiptModelDetail(inventoryReceiptModelDetail);
                    if(inventoryReceiptInfo.getReceiptType() != 5){
                        //生成库存信息
                        modelInventoryService.saveInventoryIn(inventoryReceiptInfo, inventoryReceiptModelDetail, batchNumber);
                    }else{
                        Assert.notNull(workOrderInfo, "工单信息不存在");
                        //母版加工工单则更新母版库存信息
                        modelInventoryService.updateInventoryIn(workOrderInfo.getModelInventoryId(),inventoryReceiptInfo,inventoryReceiptModelDetail);
                    }
                    inventoryNum+=inventoryReceiptModelDetail.getActualQuantity();
                }
            }
            if(inventoryReceiptInfo.getReceiptType()==3||inventoryReceiptInfo.getReceiptType()==4){
                Assert.notNull(workOrderInfo, "工单信息不存在");
                String warehouseType=inventoryReceiptInfo.getReceiptType()==3?"产成品库":"产成品母版库";
                workOrderLogService.saveLog(workOrderInfo, "工单申请入`"+warehouseType+"`，入库单编号："
                        +inventoryReceiptInfo.getReceiptNumber()+"。入库完成，入库总库存："
                        +inventoryNum
                        +"。入库批次："+batchNumber);
                workOrderInfoService.cancel(workOrderInfo.getId(),"workOrder");
            }
        }
        return update;
    }

    /**
     * 批量删除入库单信息
     *
     * @param ids 需要删除的入库单信息主键
     * @return 结果
     */
    @Override
    public int deleteInventoryReceiptInfoByIds(Long[] ids) {
        return inventoryReceiptInfoMapper.deleteInventoryReceiptInfoByIds(ids);
    }

    /**
     * 删除入库单信息信息
     *
     * @param id 入库单信息主键
     * @return 结果
     */
    @Override
    public int deleteInventoryReceiptInfoById(Long id) {
        return inventoryReceiptInfoMapper.deleteInventoryReceiptInfoById(id);
    }

    @Override
    @Transactional
    public boolean generateInventoryReceiptInfo(PurchaseOrderInfo orderInfo) {
        Assert.isTrue(!CollectionUtils.isEmpty(orderInfo.getPurchaseOrderDetailList()), "采购单明细不能为空");
        InventoryReceiptInfo receiptInfo = InventoryReceiptInfo.builder()
                .receiptType(1)
                .receiptNumber("GR" + System.currentTimeMillis())
                .warehouseId(orderInfo.getWarehouseId())
                .warehouseCode(orderInfo.getWarehouseCode())
                .supplierId(orderInfo.getSupplierId())
                .supplierCode(orderInfo.getSupplierCode())
                .handlerId(orderInfo.getHandlerId())
                .purchaseOrderId(orderInfo.getId())
                .purchaseOrderCode(orderInfo.getPurchaseOrderCode())
                .purchaseOrderAuth(orderInfo.getUpdateBy())
                .status(0)
                .build();
        receiptInfo.setCreateBy(orderInfo.getCreateBy());
        receiptInfo.setCreateTime(DateUtils.getNowDate());
        int save = inventoryReceiptInfoMapper.insertInventoryReceiptInfo(receiptInfo);
        if (save > 0) {
            for (PurchaseOrderDetail orderDetail : orderInfo.getPurchaseOrderDetailList()) {
                InventoryReceiptDetail detail = InventoryReceiptDetail.builder()
                        .receiptId(receiptInfo.getId())
                        .receiptNumber(receiptInfo.getReceiptNumber())
                        .warehouseId(orderInfo.getWarehouseId())
                        .warehouseCode(orderInfo.getWarehouseCode())
                        .materialId(Long.parseLong(orderDetail.getMaterialId()))
                        .materialCode(orderDetail.getMaterialCode())
                        .materialImage(orderDetail.getMaterialImage())
                        .materialName(orderDetail.getMaterialName())
                        .materialSpecification(orderDetail.getMaterialSpecification())
                        .expectedQuantity(orderDetail.getQuantity().longValue())
                        .actualQuantity(0L)
                        .unit(orderDetail.getUnit())
                        .build();
                detail.setRemark(orderDetail.getRemark());
                detail.setCreateBy(orderInfo.getCreateBy());
                detail.setCreateTime(DateUtils.getNowDate());
                int insert = inventoryReceiptDetailMapper.insertInventoryReceiptDetail(detail);
                Assert.isTrue(insert > 0, "入库单明细保存失败");
            }
        }
        return save > 0;
    }
}